package com.muqi.app.qlearn.adapter;

import java.util.List;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.bean.ImageItem;
import com.muqi.app.project.utils.AppUtils;
import com.muqi.app.qlearn.student.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;

public class NinePhotosAdapter extends BaseAdapter {
	private Context context;
	private List<ImageItem> listData;
	private OnDeleteListener listener;

	public NinePhotosAdapter(Context context, List<ImageItem> listData, OnDeleteListener listener) {
		this.context = context;
		this.listData = listData;
		this.listener = listener;
	}

	@Override
	public int getCount() {
		return listData == null ? 0 : listData.size();
	}

	@Override
	public ImageItem getItem(int position) {
		return listData.get(position);
	}
   
	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		final ImageItem mediainfo = listData.get(position);
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.item_picture_grid_view, null);
			holder.user_pic = (ImageView) convertView.findViewById(R.id.item_pic_view);
			holder.delete_btn = (ImageButton) convertView.findViewById(R.id.pic_delete_btn);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		LayoutParams params = holder.user_pic.getLayoutParams();
		params.height = AppUtils.dp2px(context, 80);
		params.width = AppUtils.dp2px(context, 80);
		holder.user_pic.setLayoutParams(params);
		if(mediainfo.path.equals("Add_Button")){
			holder.user_pic.setImageResource(R.drawable.imgbtn_photo_selecter);
			holder.delete_btn.setVisibility(View.GONE);
		} else {
			if (mediainfo.path.substring(0, 4).equals("http")) {
				Glide.with(context).load(mediainfo.path).error(R.drawable.imgbtn_photo_selecter).into(holder.user_pic);
			} else {
				Glide.with(context).load("file://" + mediainfo.path).error(R.drawable.imgbtn_photo_selecter).into(holder.user_pic);
			}
			holder.delete_btn.setVisibility(View.VISIBLE);
			holder.delete_btn.setVisibility(View.VISIBLE);
			holder.delete_btn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					listener.onDeletePicture(position);
				}
			});
		}
		return convertView;
	}

	public interface OnDeleteListener {
		void onDeletePicture(int position);
	}
	
	private class ViewHolder {
		ImageView user_pic;
		ImageButton delete_btn;
	}
}
